package titt.server;

import java.net.ServerSocket;
import java.net.Socket;

import titt.TITTValues;
import titt.config.ValueConfig;
import titt.head.HeadFactory;
import titt.head.Header;
import titt.head.request.Request;
import titt.head.request.RequestHead;
import titt.head.response.ResponseHead;
import titt.io.IOFactory;
import titt.io.socket.TITTSocket;
import titt.server.os.ServerValueConfig;
import titt.service.threading.MultipleTITTThreader;

public class Server {

	private final ServerJob sj;
	
	public Server(ServerJob sj) {
		this.sj = sj;
	}
	
	public void start() {
		MultipleTITTThreader.get().execute(new Runnable() {			
			public void run() {
				try {

					ServerSocket ss = new ServerSocket(ValueConfig.get().getPort());

					while(true) {
						Socket s = ss.accept();
						s.setSoTimeout(ServerValueConfig.get().getTimeout());
						s.setKeepAlive(true);
						handle(s);
					}

				}
				catch(Exception e) {

				}
			}
		});
	}

	private void handle(final Socket s) throws Exception {
		MultipleTITTThreader.get().execute(new Runnable() {			
			public void run() {
				TITTSocket ts = null;
				try {

					ts = IOFactory.createTITTSocket(s);

					RequestHead req = new Request(ts.getHeadReader().readHead());

					if(req.getHTTPMethod() == TITTValues.OPTIONS) {
						Header[] headers = new Header[]{
								new Header("Access-Control-Allow-Origin", req.getHeader("Origin").getValue()),
								new Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
						};
						ts.getHeadWriter().writeHead(new ResponseHead(200, HeadFactory.createHead(headers)));
						ts.close();
						return;
					}	
					
					sj.execute(req, ts);

				}
				catch(Exception e) {
					try {
						if(ts != null && !ts.isClosed())
							ts.close();
					}
					catch(Exception ex) {

					}
				}
			}
		});
	}
}
